package org.jeecg.modules.demo.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.crm.entity.*;
import org.jeecg.modules.demo.crm.mapper.*;
import org.jeecg.modules.demo.crm.service.ICCommonService;
import org.jeecg.modules.demo.crm.service.ICProjectApplicationService;
import org.jeecg.modules.demo.crm.service.ICProjectPreviewService;
import org.jeecg.modules.demo.crm.service.ICSubProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 项目数据看板
 * @Author: jeecg-boot
 * @Date:   2025-07-18
 * @Version: V1.0
 */
@Service
public class CProjectPreviewServiceImpl extends ServiceImpl<CProjectPreviewMapper, CProjectPreview> implements ICProjectPreviewService {

    @Autowired
    private CProjectPreviewMapper cProjectPreviewMapper;
    @Autowired
    private ICProjectApplicationService iProjectApplicationService;

    @Autowired
    private ICSubProjectService iSubProjectService;

    @Autowired
    private CSubProjectMapper cSubProjectMapper;

    @Autowired
    private CPaymentInvoiceMapper cPaymentInvoiceMapper;

    @Autowired
    CPaymentRequestMapper cPaymentRequestMapper;

    @Autowired
    CInvoiceApplyMapper cInvoiceApplyMapper;

    @Autowired
    CPaymentRecordMapper cPaymentRecordMapper;

    @Autowired
    CContractMapper cContractMapper;

    @Autowired
    CProjectQuoteMapper cProjectQuoteMapper;

    @Autowired
    CTaskMapper taskMapper;

    @Autowired
    CAcceptanceRecordMapper cAcceptanceRecordMapper;

    @Autowired
    private ICCommonService commonService;

    @Autowired
    private CProjectMarkMapper cProjectMarkMapper;

    @Override
    public IPage<CProjectPreview> queryPageList(Integer pageNo,Integer pageSize,CProjectPreview cProjectPreview) {

        Page<CProjectApplication> page = new Page<CProjectApplication>(pageNo, pageSize);
        QueryWrapper<CProjectApplication> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(cProjectPreview.getProjectId())){
            queryWrapper.eq("project_id",cProjectPreview.getProjectId());
        }
        if(StringUtils.isNotEmpty(cProjectPreview.getLibraryId())){
            List<String> libraryIds = Arrays.stream(cProjectPreview.getLibraryId().split(","))
                    .map(String::trim)
                    .map(String::valueOf)
                    .collect(Collectors.toList());
            queryWrapper.in("library_id",libraryIds);
        }
        if(StringUtils.isNotEmpty(cProjectPreview.getProjectNumber())){
            queryWrapper.like("project_number",cProjectPreview.getProjectNumber());
        }
        Boolean permissionCheck = commonService.permissionCheck();
        if(permissionCheck){
            //如果不是管理员
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String projectId = cSubProjectMapper.projectPermissions(sysUser.getId());
            if(projectId == null){
                projectId = "-1";
            }
            List<Long> idList = Arrays.stream(projectId.split(","))
                    .map(String::trim)
                    .filter(StringUtils::isNotBlank)
                    .map(Long::valueOf)
                    .collect(Collectors.toList());
            queryWrapper.in("id", idList);
        }


        IPage<CProjectPreview> data = new Page<>(pageNo, pageSize);
        IPage<CProjectApplication> projectPage = iProjectApplicationService.page(page, queryWrapper);
        List<CProjectPreview> records = projectPage.getRecords().stream().map(project->{
            CProjectPreview projectPreview=new CProjectPreview();
            projectPreview.setId(project.getId());
            projectPreview.setProjectId(project.getId());
            projectPreview.setCompanyInfoId(project.getCompanyInfoId());
            projectPreview.setLibraryId(project.getLibraryId());
            projectPreview.setProjectNumber(project.getProjectNumber());
            projectPreview.setContractingUnit(project.getContractingUnit());

            //收票｜付款
            //收票合计
            BigDecimal receiptsAndTaxTotal= cPaymentInvoiceMapper.getTotalAmountWithTaxBySubProjectId(project.getId(), null);
            projectPreview.setReceiptsAndTaxTotal(receiptsAndTaxTotal);
            //付款合计
            BigDecimal paymentTotal = cPaymentRequestMapper.getTotalAmount(project.getId());
            projectPreview.setPaymentTotal(paymentTotal);

            //开票｜收款
             /// 开票
            BigDecimal totalInvoicing = cInvoiceApplyMapper.getTotalAmountWithTax(project.getId());
            projectPreview.setTotalInvoicing(totalInvoicing);
             ///收款
            BigDecimal totalReceipts = cPaymentRecordMapper.getTotalAmount(project.getId());
            projectPreview.setTotalReceipts(totalReceipts);

            //主合同金额
            BigDecimal contractPrice = cContractMapper.contractPrice(project.getId());
            projectPreview.setContractPrice(contractPrice);

            //总子项目合同金额（含税）
            BigDecimal subProjectAmount = cContractMapper.contractSubProjectPrice(project.getId());
            projectPreview.setSubProjectAmount(subProjectAmount);

            //质保金合计
            //查询质保金 （合计）
            BigDecimal totalGuaranteeDeposit = cContractMapper.guaranteeDeposit(project.getId());
            projectPreview.setTotalGuaranteeDeposit(totalGuaranteeDeposit);

            //------数据完整
            //主项目合同
            Integer contract = cContractMapper.isContract(project.getId());
            projectPreview.setIsContract(String.valueOf(contract));
           // projectPreview.setIsContractMark(Integer.valueOf(contract));

            //子项目数量
            Integer subcontrCount = cSubProjectMapper.subcontrCount(project.getId());
            projectPreview.setSubProjectCount(subcontrCount);

            /// 标记价格
            CProjectMark cProjectMark = cProjectMarkMapper.selectByProject(project.getId());
            if(cProjectMark != null){
                projectPreview.setIsContractMark(cProjectMark.getIsContractMark());
                projectPreview.setPaymentTotalMark(cProjectMark.getPaymentTotalMark());
                projectPreview.setSubProjectAmountMark(cProjectMark.getSubProjectAmountMark());
                projectPreview.setReceiptsAndTaxTotalMark(cProjectMark.getReceiptsAndTaxTotalMark());
                projectPreview.setPaymentTotalMark(cProjectMark.getPaymentTotalMark());
                projectPreview.setTotalInvoicingMark(cProjectMark.getTotalInvoicingMark());
                projectPreview.setTotalReceiptsMark(cProjectMark.getTotalReceiptsMark());
                projectPreview.setContractPriceMark(cProjectMark.getContractPriceMark());
                projectPreview.setTotalGuaranteeDepositMark(cProjectMark.getTotalGuaranteeDepositMark());
            }else {
                projectPreview.setIsContractMark(0);
                projectPreview.setPaymentTotalMark(BigDecimal.ZERO);
                projectPreview.setSubProjectAmountMark(BigDecimal.ZERO);
                projectPreview.setReceiptsAndTaxTotalMark(BigDecimal.ZERO);
                projectPreview.setPaymentTotalMark(BigDecimal.ZERO);
                projectPreview.setTotalInvoicingMark(BigDecimal.ZERO);
                projectPreview.setTotalReceiptsMark(BigDecimal.ZERO);
                projectPreview.setContractPriceMark(BigDecimal.ZERO);
                projectPreview.setTotalGuaranteeDepositMark(BigDecimal.ZERO);
            }
            return projectPreview;
        }).collect(Collectors.toList());

        data.setRecords(records);
        data.setTotal(projectPage.getTotal());
        data.setPages(projectPage.getPages());
        data.setSize(projectPage.getSize());
        data.setCurrent(projectPage.getCurrent());
        return data;
    }

    @Override
    public IPage<CSubProjectPreview> subProjectList(Integer pageNo,Integer pageSize,CSubProjectPreview cSubProjectPreview) {
        Page<CSubProject> page = new Page<CSubProject>(pageNo, pageSize);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Boolean permissionCheck = commonService.permissionCheck();
        List<String>  subProjectIds = null;
        if(permissionCheck){
            String subProjectId = cSubProjectMapper.subProjectPermissions(sysUser.getId());
            if(subProjectId == null){
                subProjectId = "-1";
            }
           subProjectIds = Arrays.stream(subProjectId.split(","))
                    .map(String::trim)
                    .filter(StringUtils::isNotBlank)
                    .map(String::valueOf)
                    .collect(Collectors.toList());
        }

        List<String> libraryIds = null;
        if(StringUtils.isNotEmpty(cSubProjectPreview.getLibraryId())){
            libraryIds = Arrays.stream(cSubProjectPreview.getLibraryId().split(","))
                    .map(String::trim)
                    .map(String::valueOf)
                    .collect(Collectors.toList());
        }

        IPage<CSubProject> subProjectPage = cSubProjectMapper.selectSubProjectWithConditions(page, subProjectIds, cSubProjectPreview.getProjectId(),
                libraryIds, cSubProjectPreview.getSubProjectTitle());

       List<CSubProjectPreview> records = subProjectPage.getRecords().stream().map(subProject->{
            CSubProjectPreview subProjectPreview=new CSubProjectPreview();
            subProjectPreview.setId(subProject.getId());
            subProjectPreview.setSubProjectId(subProject.getId());
            subProjectPreview.setProjectId(subProject.getProjectId());
            subProjectPreview.setUserId(subProject.getUserId());
            subProjectPreview.setContactId(subProject.getContactId());
            subProjectPreview.setSubProjectTitle(subProject.getSubProjectName());
            subProjectPreview.setLibraryId(subProject.getLibraryId());
            //
           //收票｜付款
           //收票合计
           BigDecimal receiptsAndTaxTotal= cPaymentInvoiceMapper.getTotalAmountWithTaxSub(subProject.getProjectId(), subProject.getId());
           subProjectPreview.setReceiptsAndTaxTotal(receiptsAndTaxTotal);
           //付款合计
           BigDecimal paymentTotal = cPaymentRequestMapper.getPaymentAmount(subProject.getProjectId(), subProject.getId());
           subProjectPreview.setPaymentTotal(paymentTotal);

           //报价
           Integer isQuote = cProjectQuoteMapper.findBySubProjectIdCount(subProject.getId(),"报价完成");
           subProjectPreview.setIsProjectQuote(String.valueOf(isQuote));
           subProjectPreview.setProjectQuoteCount(cProjectQuoteMapper.subProjectIdCount(subProject.getId()));

           //是否上传合同
           Integer contract = cContractMapper.isContractBySubProject(subProject.getProjectId(),subProject.getId());
           subProjectPreview.setIsContract(String.valueOf(contract));

           //任务
           Integer unfinished = taskMapper.unfinished(subProject.getId());
           subProjectPreview.setIsTask(String.valueOf(unfinished));
           subProjectPreview.setTaskCount(taskMapper.subProjectCount(subProject.getId()));

           //验收
           Integer notAccepted = cAcceptanceRecordMapper.notAccepted(subProject.getId());
           subProjectPreview.setIsAcceptance(String.valueOf(notAccepted));
           subProjectPreview.setAcceptanceCount(cAcceptanceRecordMapper.subProjectCount(subProject.getId()));



           return subProjectPreview;
        }).collect(Collectors.toList());

        IPage<CSubProjectPreview> data=new Page<>(pageNo, pageSize);
        data.setRecords(records);
        data.setTotal(subProjectPage.getTotal());
        data.setPages(subProjectPage.getPages());
        data.setSize(subProjectPage.getSize());
        data.setCurrent(subProjectPage.getCurrent());
        return data;
    }
}
